<!--#include file="config.asp"-->
<%
''' SDCMS QQ登录处理
''' ==================================================================
''' 版权所有 http://www.sdcms.cn
''' ------------------------------------------------------------------
''' 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；
''' 未经授权不允许对程序代码以任何形式任何目的的再发布。
''' ==================================================================
''' 编写: IT平民
''' 修改：IT平民 in 2012.0

	sub callback()
		dim states:states=sdcms.enhtml(sdcms.fget("state",0))
		dim code:code=sdcms.enhtml(sdcms.fget("code",0))
		dim t0:t0=sdcms.enhtml(sdcms.loadsession("qq_state"))
		if t0="" then
			sdcms.echo "会话过期，无法登录"
			exit sub
		end if
		if sdcms.strlen(states)=0 or sdcms.strlen(code)=0 then
			sdcms.echo "非法参数传递，无法登录"
			exit sub
		end if
		if states<>t0 then
			sdcms.echo "登录验证失败，无法登录"
			exit sub
		else
			dim url:url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"
				url=url&"&client_id="&qq_appid
				url=url&"&client_secret="&qq_appkey
				url=url&"&redirect_uri="&qq_callback
				url=url&"&code="&code
			dim str:str=sdcms.gethttp(url,"")
			if instr(str,"callback")>0 then
				str=replace(str,"callback( ","")
				str=replace(str," )","")
				dim json
				set json=toobject(str)
					sdcms.echo "错误编号："&sdcms.enhtml(json.error)&"<br>"
					sdcms.echo "错误原因："&sdcms.enhtml(json.error_description)&"<br>"
				set json=nothing
				exit sub
			end if
			if left(str,13)="access_token=" then
				dim access_token:access_token=mid(str,14,instr(str,"&")-14)
				sdcms.setsession "access_token",sdcms.enhtml(access_token)
			else
				sdcms.echo "未知错误"
				exit sub
			end if
		end if
	end sub
	
	sub get_openid()
		dim url:url="https://graph.qq.com/oauth2.0/me?access_token="&sdcms.loadsession("access_token")
		dim str:str=sdcms.gethttp(url,"")
		dim gourl:gourl=sdcms.loadsession("api_backurl")
		if instr(str,"callback")>0 then
			str=replace(str,"callback( ","")
			str=replace(str," )","")
			dim json
			set json=toobject(str)
			dim openid:openid=sdcms.enhtml(json.openid)
				sdcms.setsession "openid",openid
			set json=nothing
			'查询openid，如果存在则直接获取会员信息，否则跳转到绑定页面
			dim data:data=sdcms.db.dbload(1,"n.userid,u.logintimes","sd_user_bind n left join sd_user u on n.userid=u.id","n.openid='"&openid&"' and n.opentype='qq'","")
			if ubound(data)<0 then
				sdcms.setsession "api_backurl",""
				sdcms.go "bind.asp?api_backurl="&gourl
				exit sub
			else
				sdcms.db.dbupdate "sd_user","id="&data(0,0)&"",array(array("logintimes",data(1,0)+1,0,0))
				sdcms.resetuserinfo("u.id="&data(0,0)&"")
				'清空API数据
				sdcms.setsession "qq_state",""
				sdcms.setsession "access_token",""
				sdcms.setsession "openid",""
				sdcms.setsession "api_backurl",""
				if sdcms.strlen(gourl)=0 then gourl=webroot
				sdcms.go gourl
			end if
		else
			sdcms.echo "无法获取数据，登录失败"
			exit sub
		end if
	end sub

	callback()
	get_openid()
%>